package cn.ylg.com.ontouchdemo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by MyPC on 2016/10/17.
 */
public class TransaltingActivity extends Activity implements View.OnTouchListener{
    private static final long DURATION = 200;
    private View activity_transalting;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transalting);
        activity_transalting = findViewById(R.id.activity_transalting);
        activity_transalting.setOnTouchListener(this);
    }

    float startintX = 0;//手指落下的位置;
    boolean isDraging = false;
    /*如果手指点再屏幕某处,系统会不断的调用onTouch()方法*/
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //获取相对于屏幕的x轴坐标
        float rawX = event.getRawX();
        switch (event.getAction()){
            //手指落下的位置;
            case MotionEvent.ACTION_DOWN:
                if (rawX<getScreenWidth()/9){//当手指在屏幕的左侧边界处才能够移动界面;
                    startintX = rawX;
                    activity_transalting.setX(rawX);
                    isDraging = true;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (isDraging){
                    activity_transalting.setX(event.getRawX());
                }
                break;
            case MotionEvent.ACTION_UP:
                //如果超过屏幕的一半,而且是可以打开的状态 activity就被finish掉
                if (rawX - startintX > getScreenWidth()/2 && isDraging){
                    activity_transalting.animate().translationX(getScreenWidth())
                            .setDuration(DURATION)
                            .setListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    super.onAnimationEnd(animation);
                                    finish();
                                }
                            });
                }else{
                    activity_transalting.animate().translationX(0);
                    isDraging = false;
                }
                break;
        }
        return true;
    }

    //获取屏幕的宽度;
    private int getScreenWidth() {
        return getResources().getDisplayMetrics().widthPixels;
    }
}
